package com.guodidi.media.util;

import com.google.common.base.Stopwatch;
import com.guodidi.media.domain.bo.CommonParams;
import com.guodidi.media.domain.entity.Hls;
import com.guodidi.media.domain.enums.TraverTypeE;

import java.io.IOException;
import java.nio.file.Files;
import java.time.Duration;
import java.util.List;

/**
 * Created by 郭垚辉 on 2017/7/26.
 */
public class CmdUtils {

    /**
     * 执行命令行后，返回当前的所有的文件(m3u8+ts)的路径集合
     */
    private static void process(List<String> command, CommonParams params) throws IOException {
        Stopwatch watch = Stopwatch.createStarted();
        ProcessBuilder builder = new ProcessBuilder(command);

        // 将命令行的工作目录切换到目标目录。否则会将目录在当前的执行路径下生成
        if (Files.notExists(params.getWorkPath())) {
            Files.createDirectories(params.getWorkPath());
        }
        builder.directory(params.getWorkPath().toFile());

        builder.redirectErrorStream(true);
        Process process = null;
        try {
            System.out.println("执行命令: " + CmdUtils.showCmd(command));
            process = builder.start();
            StreamUtils.showMessage(process.getInputStream());
            Duration elapsed = watch.elapsed();
            System.out.println("命令执行完毕共用了" + elapsed.getSeconds() + "秒");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            process.destroy();
        }
    }

    /**
     * 显示当前执行的命令行参数
     */
    private static String showCmd(List<String> cmdList) {
        StringBuffer buffer = new StringBuffer();
        for (String cmd : cmdList) {
            buffer.append(cmd).append(" ");
        }
        return buffer.toString();
    }

    public static Hls processCovertEvent(List<String> list, CommonParams params) throws IOException {
        CmdUtils.process(list, params);
        Hls targetHls = params.getTargetHls();
        FileUtils.moveFile(params.getVirtualDestPath(), params.getRealDestPath(), false);
        targetHls.setTsPaths(FileUtils.traverseDirectory(params.getVirtualDestPath().getParent(), TraverTypeE.CURRENT_DIR));
//        params.getTargetHls().setTsPaths();
        return targetHls;
    }

}
